#include <windows.h>
#include <stdio.h>
#include "engine.h"
#ifdef _DEBUG
	/* Required for connecting IO streams to the console in debug mode. */
	#include <io.h>
	#include <fcntl.h>
#endif

#define WINDOW_WIDTH 	640
#define WINDOW_HEIGHT 	480

#ifdef _DEBUG
FILE *fpIn, *fpOut;

#include <SDL.h>

//===============================================================
// Opens a console window for debug messages.
//===============================================================
void OpenConsole()
{
	AllocConsole();

	/* Connect the output stream to the console. */
	HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
	int hCrt = _open_osfhandle((long)hStdOut, _O_TEXT);
	fpOut = _fdopen(hCrt, "w");
	setvbuf(fpOut, NULL, _IONBF, 1);
	*stdout = *fpOut;

	/* Connect the input stream to the console. */
	HANDLE hStdIn = GetStdHandle(STD_INPUT_HANDLE);
	hCrt = _open_osfhandle((long)hStdIn, _O_TEXT);
	fpIn = _fdopen(hCrt, "r");
	setvbuf(fpIn, NULL, _IONBF, 128);
	*stdin = *fpIn;
}

//===============================================================
// Closes the debug console.
//===============================================================
void CloseConsole()
{
	if (fpOut)
		fclose(fpOut);

	if (fpIn)
		fclose(fpIn);
}
#endif

//===============================================================
// Message handler for the game window.
//===============================================================
LRESULT CALLBACK WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	switch ( uMsg )
	{
		case WM_DESTROY:
		{
			PostQuitMessage( 0 );
		}
		return 0;
	}
	return DefWindowProc( hWnd, uMsg, wParam, lParam );
}

//===============================================================
// Main entry point of the application.
//===============================================================
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd )
{
	#if defined(_DEBUG) && defined(_CONSOLE)
	OpenConsole();
	#endif

	/* Initialize SDL. */
	SDL_Init(SDL_INIT_VIDEO);
	SDL_WM_SetCaption("Pokemon Online", 0);
	atexit(SDL_Quit);

	/* Initialize the game engine. */
	CEngine *engine = CEngine::Initialize(NULL, hInstance, WINDOW_WIDTH, WINDOW_HEIGHT);

	/* Start the main game loop. */
	SDL_Event event;
	while (engine->IsRunning())
	{
		while (SDL_PollEvent(&event))
			engine->HandleEvent(&event);

		engine->Think(GetTickCount());
	}
	CEngine::Deinitialize();

	#if defined(_DEBUG) && defined(_CONSOLE)
	CloseConsole();
	#endif

	return 0;
}
